package com.awenhui.demo.config.feign;

import com.awenhui.demo.config.feign.strategy.safety.ContextSafetyStrategy;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Feign 拦截器
 * @author heliuh
 * @version 1.0
 * @date 2021/7/2 15:59
 */
@Component
@Slf4j
public class FeignInterceptor implements RequestInterceptor {

    @Autowired
    ContextSafetyStrategy contextSafetyStrategy;

    @Override
    public void apply(RequestTemplate requestTemplate) {

        log.info("------------FeignInterceptor------------>apply:{}", "执行feign拦截器");
        // 获取基本参数
        Map<String, String> strategies = getParams(requestTemplate);
        //根据策略来设置不同的请求头和请求数据
        requestTemplate.header("author","何刘惠");
        requestTemplate.header("feign-token", UUID.randomUUID().toString());
        // 处理数据安全
        String safetyStrategy = strategies.get("safetyStrategy");
        if (StringUtils.isNotBlank(safetyStrategy)) {
            contextSafetyStrategy.handleSafety(safetyStrategy, requestTemplate);
        }
    }
    /**
     * 获取策略基本信息
     *
     * @param template ${@link RequestTemplate}
     * @return Map ${@link Map}
     * @author zxiaozhou
     * @date 2019-06-14 12:11
     */
    private Map<String, String> getParams(RequestTemplate template) {
        Map<String, Collection<String>> queries = new LinkedHashMap<>(template.queries());
        Map<String, String> strategies = new HashMap<>(2);
        if (!queries.isEmpty()) {
            // 获取请求头设置策略
            Collection<String> headerStrategy = queries.remove("headerStrategy");
            if (!CollectionUtils.isEmpty(headerStrategy)) {
                String strategy = new ArrayList<>(headerStrategy).get(0);
                if (StringUtils.isNotBlank(strategy)) {
                    log.debug("----------FeignInterceptor---------->getParams:{}", "执行feign拦截器,当前需要设置请求头,调用策略" + strategy);
                    strategies.put("headerStrategy", strategy);
                }
            }
            // 获取数据安全设置策略
            Collection<String> safetyStrategy = queries.remove("safetyStrategy");
            if (!CollectionUtils.isEmpty(safetyStrategy)) {
                String strategy = new ArrayList<>(safetyStrategy).get(0);
                if (StringUtils.isNotBlank(strategy)) {
                    log.debug("----------FeignInterceptor---------->getParams:{}", "执行feign拦截器,当前数据需要安全处理,调用策略" + strategy);
                    strategies.put("safetyStrategy", strategy);
                }
            }
        }
        // 重置请求地址参数
        template.queries(null);
        template.queries(queries);
        return strategies;
    }
}
